package com;

import com.data.DataService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.feign.BowlFeign;
import com.feign.LocalRecApiFeign;
import com.feign.YsApiFeign;
import com.model.ImgTag;
import com.model.ProductRecResultVO;
import com.model.ProductRecResultVONewWithLocation;
import com.model.ProductYpRef;
import com.model.imgrec.ImgRecResult;
import com.request.*;
import com.response.ResultGenerator;
import com.response.ShopProductMessageVO;
import com.response.hkym.*;
import com.service.ProductService;
import com.service.UploadService;
import com.util.FileDownloader;
import com.util.ImageBase64Util;
import com.util.JsonUtil;
import com.util.ThreadManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import com.response.ProductVO;
import com.response.Result;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.*;
import java.util.stream.Collectors;

import static com.data.DataService.localModelFilepath;

@SpringBootApplication
@RestController
@EnableScheduling
@EnableFeignClients
public class ServerApplication implements InitializingBean {

    private static Logger logger = LoggerFactory.getLogger(ServerApplication.class);

    public static boolean scheduling = false;
    public static boolean productImgscheduling = false;

    @Autowired
    LocalRecApiFeign localRecApiFeign;

    @Autowired
    YsApiFeign ysApiFeign;

    @Autowired
    ProductService productService;

    @Autowired
    UploadService uploadService;

    @Autowired
    BowlFeign bowlFeign;

    BASE64Decoder decoder = new BASE64Decoder();

    private List<Integer> directoryCreatedShopIdList = new ArrayList<>();

    public static void main(String[] args) throws Exception {
        System.out.println(System.currentTimeMillis());
        File imgPath = new File(DataService.imgPath);
        if (!imgPath.exists()) {
            imgPath.mkdir();
        }

        File images = new File(DataService.imgPath + File.separator+"images");
        if (!images.exists()) {
            images.mkdir();
        }

        File source = new File(DataService.imgPath + File.separator+"images"+File.separator+"source"+File.separator);
        if (!source.exists()) {
            source.mkdir();
        }

        File yppos = new File(DataService.imgPath + File.separator+"images"+File.separator+"yppos"+File.separator);
        if (!yppos.exists()) {
            yppos.mkdir();
        }

        SpringApplication.run(ServerApplication.class, args);
    }


    @GetMapping("/api/setBranchId")
    public Result setBranchId(@RequestParam("branchId")Integer branchId,
                              @RequestParam("shopId")Integer shopId) throws Exception{

        logger.info("setBranchId===branchId={}, shopId={}", branchId, shopId);
        if (branchId != null && branchId > 0) {
            DataService.branchId = branchId;
            DataService.shopId = shopId;

            FileWriter fileWriter = new FileWriter(DataService.imgPath + File.separator + "branchId.txt");
            fileWriter.write(branchId + "");
            fileWriter.close();

            FileWriter shopIdFileWriter = new FileWriter(DataService.imgPath + File.separator + "shopId.txt");
            shopIdFileWriter.write(shopId + "");
            shopIdFileWriter.close();

            updateProductData();
            return ResultGenerator.genSuccessResult();
        }

        return ResultGenerator.genFailResult("参数错误");

    }


    @PostMapping("/api/product/correct")
    public Result upload(@RequestBody ProductCorrectForm productCorrectForm) throws Exception{

//        logger.info("productCorrectForm=" + JsonUtil.toJson(productCorrectForm));
        logger.info("productCorrectForm=" + JsonUtil.toJson(productCorrectForm));

        boolean recResult = productService.correctProductImg(productCorrectForm);


        ThreadManager.executorService.submit(() -> {
            logger.info("开始上传服务器========================productCorrectFor");
            if (recResult) {
                Result result = localRecApiFeign.uploadCorrect(productCorrectForm);
                try {
                    logger.info("结束上传服务器========================result=" + JsonUtil.toJson(result));
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            }
        });

        if (recResult) {
            return ResultGenerator.genSuccessResult();
        }else {

            return ResultGenerator.genFailResult("失败");
        }
    }


    @PostMapping("/api/product/recWithLocation")
    public Result recWithLocationAndHuawei(@RequestBody ProductRecForm productRecForm) {
        long startTime = System.currentTimeMillis();
        logger.info("recWithLocation startTime=" + startTime + "productRecForm.type====" + productRecForm.getType());
        StringBuffer filePathStringBuffer = new StringBuffer(DataService.imgPath + File.separator +
                "images" + File.separator + "source" + File.separator);
        filePathStringBuffer.append(DataService.branchId);

        StringBuffer outputFilepathStringBuffer = new StringBuffer(DataService.imgPath +
                File.separator + "images" + File.separator + "yppos" + File.separator)
                .append(DataService.branchId);

        if (!directoryCreatedShopIdList.contains(productRecForm.getShopId())) {
            directoryCreatedShopIdList.add(productRecForm.getShopId());
            File dir = new File(filePathStringBuffer.toString());
            File dirOutput = new File(outputFilepathStringBuffer.toString());
            if (!dir.exists()) {
                dir.mkdir();
            }
            if (!dirOutput.exists()) {
                dirOutput.mkdir();
            }
        }

        String uuid = UUID.randomUUID().toString();

        String newFileName = filePathStringBuffer.append(File.separator).append(uuid).append(".png").toString();

        String outputFilepath = outputFilepathStringBuffer.append(File.separator).append(uuid).append(".result.png").toString();

        String tempSourceUrl = "";
        try {
//            byte[] bytes1 = decoder.decodeBuffer(productRecForm.getFileContent());
//            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
//            BufferedImage bi1 = ImageIO.read(bais);
//
//            File f1 = new File(newFileName);
//            ImageIO.write(bi1, "png", f1);


            logger.info("上传成功:newFileName==" + newFileName);

            long endTime = System.currentTimeMillis();
            logger.info("endTime=" + endTime + ", intelval=" + (endTime - startTime));

            StringBuffer imgUrl = null;

            Integer branchId = null;
            StringBuffer sourceImgUrl = new StringBuffer("http://")
                    .append(DataService.localIp)
                    .append("/images/source/")
                    .append(DataService.branchId)
                    .append("/").append(uuid).append(".png");

            tempSourceUrl = sourceImgUrl.toString();

            imgUrl = new StringBuffer("http://")
                    .append(DataService.localIp)
                    .append("/images/yppos/")
                    .append(DataService.branchId)
                    .append("/").append(uuid).append(".result.png");


            logger.info("上传成功:branchId==" + branchId);

            logger.info("上传成功:newFileName==" + newFileName);
            logger.info("上传成功:outputFilepath==" + outputFilepath);
            ProductRecResultVONewWithLocation result = productService.searchWithPalletCell(productRecForm.getShopId(), productRecForm.getFileContent()
                    , newFileName, outputFilepath, uuid, imgUrl.toString(), sourceImgUrl.toString()
                    ,  DataService.branchId, productRecForm.getType());

            logger.info("开始上传服务器=========================" + outputFilepath);
            ThreadManager.executorService.submit(() -> {
                logger.info("开始上传服务器=======================result==" + result);
                uploadService.uploadRecResult(productRecForm.getFileContent(), result);
                logger.info("结束上传服务器=======================result==" + result);
            });
            logger.info("结束上传服务器=========================" + outputFilepath);

            long resultTime = System.currentTimeMillis();
            logger.info("结束识别，耗时=========================" + (resultTime-startTime));


            if (result != null) {
                result.setProductOrderNo(uuid);
                result.setImgUrl(imgUrl.toString());
                logger.info(JsonUtil.toJson(result));
                return ResultGenerator.genSuccessResult(result);
            }
            return ResultGenerator.genFailResult("error");
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.toString());
        }

        ProductRecResultVO result = new ProductRecResultVO();


        result.setImgUrl(tempSourceUrl);

        return ResultGenerator.genSuccessResult(result);
    }

    @PostMapping("/api/product/localrec")
    public Result localrec(@RequestParam("file") MultipartFile file,
                          @RequestParam("port")int port,
                          HttpServletResponse response) {


        String filePath = "D:\\jay\\" + System.currentTimeMillis() + ".jpg";
//        String filePath = "/Users/jay/IdeaProjects/binguo/LocalRec/target/" + System.currentTimeMillis() + ".jpg";
        File dest = new File(filePath);

        try {
            file.transferTo(dest);
            String resultStr = productService.sendMsg9005(filePath, port);
            return ResultGenerator.genSuccessResult(resultStr);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResultGenerator.genFailResult("");

    }


  /*  @GetMapping("/api/product/generate")
    public Result generateFiles() throws Exception{

        File folder = new File(DataService.imgPath + "/716_check");
        File[] fileList = folder.listFiles();
        File checkedFolder = new File(DataService.imgPath + "/716_check");
        File[] checkedFileList = checkedFolder.listFiles();

        List<String> checkedFileNameList = new ArrayList<>();
        for (File checkedFile : checkedFileList) {
            checkedFileNameList.add(checkedFile.getName());
            logger.info(checkedFile.getName());
        }


        *//**
         * {"ZC-Bao_Zi": {"id": "2019581", "name": "包子", "price": 0.01}, "ZC-You_Tiao":
         * {"id": "2019582", "name": "油条", "price": 0.01},
         * "ZC-Man_Tou": {"id": "2019583", "name": "馒头", "price": 0.01},
         * "ZC-Ji_Dan": {"id": "2019584", "name": "鸡蛋", "price": 0.01},
         * "ZC-Ji_Dan_Geng": {"id": "2019585", "name": "鸡蛋羹", "price": 0.01},
         * "ZC-Mi_Fan": {"id": "2019586", "name": "早餐", "price": 0.01},
         * "YLSG-Le_Chang_Suan_Nai": {"id": "2019587", "name": "乐畅酸奶", "price": 0.01},
         * "ZC-Xiang_Jiao": {"id": "2019588", "name": "香蕉", "price": 0.01},
         * "ZC-Ju_Zi": {"id": "2019589", "name": "橘子", "price": 0.01},
         * "YLSG-Ping_Guo": {"id": "20195810", "name": "苹果", "price": 0.01}}
         *//*
        Map<String, String> kv = new HashMap<>();
//        kv.put("2019581", "包子");
        kv.put("2019582", "油条");
        kv.put("2019583", "馒头");
        kv.put("2019584", "鸡蛋");
        kv.put("2019585", "鸡蛋羹");
//        kv.put("2019586", "早餐");
        kv.put("2019587", "乐畅酸奶");
        kv.put("2019588", "香蕉");
        kv.put("2019589", "橘子");
        kv.put("20195810", "苹果");

        for (File file : fileList) {
            BufferedImage bi1 = ImageIO.read(file);

            if (bi1 == null) {
                continue;
            }

            *//*if (checkedFileNameList.contains(file.getName())) {
                logger.info("contains:{}", file.getName());
                continue;
            }*//*

            int width = bi1.getWidth();

            if (width < 1024) {
                continue;
            }

            BowlForm bowlForm = new BowlForm();
            bowlForm.setImgUrl(file.getAbsolutePath().replaceAll(DataService.imgPath, DataService.netUrl));
            bowlForm.setShopId("1");
            logger.info("bowlForm=={}", JsonUtil.toJson(bowlForm));
            String resultStr = bowlFeign.sendMsg9005(bowlForm);
            resultStr = resultStr.substring(resultStr.indexOf("results") - 2);
            logger.info("resultStr=={}", resultStr);
            ImgRecResult resResult = JsonUtil.parse(resultStr, ImgRecResult.class);
            if (resResult.getNumber() > 0) {
                List<ImgTag> imgTagList = new ArrayList<>();

                String content = "";

                String header = "<?xml version=\"1.0\" ?>\n" +
                        "<annotation>\n" +
                        "    <folder>src</folder>\n" +
                        "    <filename>fffffff</filename>\n" +
                        "    <path>E:\\src\\20200429_150703.jpg</path>\n" +
                        "    <source>\n" +
                        "        <database>Unknown</database>\n" +
                        "    </source>\n" +
                        "    <size>\n" +
                        "        <width>1280</width>\n" +
                        "        <height>1024</height>\n" +
                        "        <depth>3</depth>\n" +
                        "    </size>\n" +
                        "\n" +
                        "    <segmented>0</segmented>\n";

                header = header.replace("fffffff", file.getName());

                content += header;

                String bowlTemplate = "<object>\n" +
                        "        <name>wan</name>\n" +
                        "        <pose>Unspecified</pose>\n" +
                        "        <truncated>0</truncated>\n" +
                        "        <difficult>0</difficult>\n" +
                        "        <bndbox>\n" +
                        "            <xmin>xxxxx1111</xmin>\n" +
                        "            <ymin>yyyyy1111</ymin>\n" +
                        "            <xmax>xxxxx2222</xmax>\n" +
                        "            <ymax>yyyyy2222</ymax>\n" +
                        "        </bndbox>\n" +
                        "    </object>\n";
                for(com.model.imgrec.Results results : resResult.getResults()){
//                    if (kv.containsKey(results.getName()) && results.getScore() > 0.8) {
                    if (results.getName().equals("20191001") && results.getScore() > 0.9) {
                        int x1 = results.getLocation().getLeft();
                        int y1 = results.getLocation().getTop();

                        int x2 = results.getLocation().getLeft() + results.getLocation().getWidth();
                        int y2 = results.getLocation().getTop() + results.getLocation().getHeight();

                        ImgTag imgTag = new ImgTag();
                        imgTag.setX1(x1);
                        imgTag.setY1(y1);
                        imgTag.setX2(x2);
                        imgTag.setY2(y2);
                        imgTag.setLabel("碗");
//                        imgTag.setLabel(kv.get(results.getName()));
                        imgTag.setScore(1);
                        imgTagList.add(imgTag);

                        imgTagList.add(imgTag);

                        String temp = bowlTemplate.replaceAll("xxxxx1111", "" + x1);
                        temp = temp.replaceAll("yyyyy1111", "" + y1);
                        temp = temp.replaceAll("xxxxx2222", "" + x2);
                        temp = temp.replaceAll("yyyyy2222", "" + y2);

                        content += temp;
                    }
                }

                if (imgTagList.size() == 0) {
                    continue;
                }else {
                    *//*File newFile = new File(DataService.imgPath + "/716_needlabel/" + file.getName());
                    FileCopyUtils.copy(file, newFile);*//*
                }

                content += "</annotation>";

                File newXmlFile = new File(DataService.imgPath + "/716_bowl/label/" + file.getName().replace("png", "xml"));

                FileWriter fileWriter = new FileWriter(newXmlFile);
                fileWriter.write(content);
                fileWriter.close();

                String imgJson = JsonUtil.toJson(imgTagList);

                String url = DataService.localDrawUrl + "/hello2";

                String outputFilepath = DataService.localImgFilePath + "/716_bowl/labelimg/" + file.getName();
                String filename = file.getAbsolutePath().replaceAll(DataService.imgPath, DataService.localImgFilePath);

                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders headers = new HttpHeaders();

                SortedMap<String, String> map = new TreeMap<>();
                map.put("outputFilepath", outputFilepath);
                map.put("filename", filename);
                map.put("image", imgJson);
                MultiValueMap postMap = new LinkedMultiValueMap();
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    postMap.add(entry.getKey(),entry.getValue());
                }

                try {
                    logger.info(JsonUtil.toJson(map));
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }

                headers.add("Content-Type", "application/x-www-form-urlencoded");
                HttpEntity requestBody = new HttpEntity(postMap, headers);
                ResponseEntity<String> drwaImgResult = restTemplate.postForEntity(url, requestBody, String.class);

                String body = drwaImgResult.getBody();
                logger.info("body:{}", body);
            }
        }

        return ResultGenerator.genFailResult("");

    }
*/
    @PostMapping("/api/product/rec3")
    public Result upload3(@RequestParam("file") MultipartFile file,
                          @RequestParam("shopId")Integer shopId,
                          @RequestParam("deviceId")String deviceId,
                          @RequestParam(value = "productOrderNo", required = false)String productOrderNo,
                          @RequestParam(value = "recType", required = false)Integer recType,
                          HttpServletResponse response) {


        String filePath = DataService.imgPath + "/predict/" +System.currentTimeMillis() + ".jpg";
//        String filePath = "c:\\html\\"+System.currentTimeMillis() + ".jpg";
        File dest = new File(filePath);

        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String content = ImageBase64Util.getImageBinary(filePath);


        long startTime = System.currentTimeMillis();
        logger.info("recWithLocation startTime=" + startTime);
        StringBuffer filePathStringBuffer = new StringBuffer(DataService.imgPath + File.separator+
                "images"+File.separator+"source"+File.separator);
        filePathStringBuffer.append(DataService.branchId);

        StringBuffer outputFilepathStringBuffer = new StringBuffer(DataService.imgPath +
                File.separator+"images"+File.separator+"yppos"+File.separator)
                .append(DataService.branchId);

        if (!directoryCreatedShopIdList.contains(shopId)) {
            directoryCreatedShopIdList.add(shopId);
            File dir = new File(filePathStringBuffer.toString());
            File dirOutput = new File(outputFilepathStringBuffer.toString());
            if (!dir.exists()) {
                dir.mkdir();
            }
            if (!dirOutput.exists()) {
                dirOutput.mkdir();
            }
        }

        String uuid = UUID.randomUUID().toString();

        String newFileName = filePathStringBuffer.append(File.separator).append(uuid).append(".png").toString();

        String outputFilepath = outputFilepathStringBuffer.append(File.separator).append(uuid).append(".result.png").toString();

        String tempSourceUrl = "";
        try {
            byte[] bytes1 = decoder.decodeBuffer(content);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            BufferedImage bi1 = ImageIO.read(bais);

            File f1 = new File(newFileName);
            ImageIO.write(bi1, "png", f1);


            logger.info("上传成功:newFileName==" + newFileName);

            long endTime = System.currentTimeMillis();
            logger.info("endTime=" + endTime + ", intelval=" + (endTime - startTime));

            ProductRecResultVONewWithLocation result = null;

            StringBuffer imgUrl = null;

            Integer branchId = null;
            StringBuffer sourceImgUrl = new StringBuffer("http://")
                    .append(DataService.localIp)
                    .append(":8019/images/source/")
                    .append(DataService.branchId)
                    .append("/").append(uuid).append(".png");

            tempSourceUrl = sourceImgUrl.toString();

            imgUrl = new StringBuffer("http://")
                    .append(DataService.localIp)
                    .append(":8019/images/yppos/")
                    .append(DataService.branchId)
                    .append("/").append(uuid).append(".result.png");


            logger.info("上传成功:branchId==" + DataService.branchId);

            logger.info("上传成功:newFileName==" + newFileName);
            logger.info("上传成功:outputFilepath==" + outputFilepath);
            if (result == null) {
                result = productService.searchWithPalletCell(shopId, content
                        , newFileName, outputFilepath, uuid, imgUrl.toString(), sourceImgUrl.toString()
                        ,  DataService.branchId, recType);
            }

            if (result != null) {
                result.setProductOrderNo(uuid);
                result.setImgUrl(imgUrl.toString());
                logger.info(JsonUtil.toJson(result));
                return ResultGenerator.genSuccessResult(result);
            }
            return ResultGenerator.genFailResult("error");
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.toString());
        }

        ProductRecResultVO result = new ProductRecResultVO();


        result.setImgUrl(tempSourceUrl);

        return ResultGenerator.genSuccessResult(result);
    }

    /**
     * 每30秒同步后台产品列表
     */
    @Scheduled(cron="0/10 * * * * ?") //每30秒更新
    public void syncProductImg() throws Exception{

        try {
            if (productImgscheduling) {
                return;
            }
            logger.info("syncProductImg start====");
            productImgscheduling = true;
            Result result = localRecApiFeign.getProductImgList(DataService.branchId);
            if (result != null && result.getCode() == 200) {
                List<LinkedHashMap> shopProductMessageVOList = (List<LinkedHashMap>)result.getData();
                logger.info("shopProductMessage===={}", JsonUtil.toJson(shopProductMessageVOList));
                for (LinkedHashMap map : shopProductMessageVOList) {
                    if ((Integer)map.get("msgType") == 1) {//消息类型：1:添加 0:删除图片 2：删除产品
                        productService.addImg((String) map.get("url"), (Integer) map.get("pid"));
                    }else if ((Integer)map.get("msgType") == 0) {//消息类型：1:添加 0:删除图片 2：删除产品
                        productService.delImg((String) map.get("url"), (Integer) map.get("pid"));
                    }else if ((Integer)map.get("msgType") == 2) {//消息类型：1:添加 0:删除图片 2：删除产品
                        productService.delProduct((Integer) map.get("pid"));
                    }else if ((Integer)map.get("msgType") == 3) {//消息类型：1:添加 0:删除图片 2：删除产品 3:模型更新
                        String modelUrl = (String) map.get("url");
                        FileDownloader.downloadNet(modelUrl, localModelFilepath);
                    }
                }
            }
            logger.info("syncProductImg end====");
            productImgscheduling = false;

        } catch (Exception e) {
            productImgscheduling = false;

        }
    }

    /**
     * 每30秒同步后台产品列表
     */
    @Scheduled(cron="0/30 * * * * ?") //每30秒更新
    public void shopProductUpdate() throws Exception{
        try {
            if (scheduling) {
                return;
            }
            logger.info("shopProductUpdate start====");
            scheduling = true;
            if (DataService.branchId == null) {
                getIpList();
            }

            if (DataService.shopId != null) {
                ShopProductVersionForm shopProductVersionForm = new ShopProductVersionForm();
                shopProductVersionForm.setDeviceId(DataService.deviceId);
                shopProductVersionForm.setShopId(DataService.shopId);

                logger.info("getProductVersion===param={}", JsonUtil.toJson(shopProductVersionForm));
                Result result = localRecApiFeign.getProductVersion(shopProductVersionForm);
                logger.info("getProductVersion===result={}", JsonUtil.toJson(result));
                if (result.getCode() == 200) {
                    if (result.getData() != null) {
                        Integer version = (Integer) result.getData();

                        if (DataService.producetVersion == null) {
                            DataService.producetVersion = version;
                            DataService.productList = getProductList();
                            DataService.ypProductList = getYpProductList();
                            scheduling = false;
                            return;
                        }

                        if (version > DataService.producetVersion) {
                            DataService.productList = getProductList();
                            DataService.ypProductList = getYpProductList();
                            scheduling = false;
                            DataService.producetVersion = version;
                            return;
                        }
                    }
                }
            }
            logger.info("shopProductUpdate end====");
            scheduling = false;
        } catch (Exception e) {
            scheduling = false;
        }
    }

    public List<ProductVO> getProductList()throws Exception{
        if (DataService.shopId != null) {
            Result result = localRecApiFeign.getProductList(DataService.shopId, null,
                    null, DataService.deviceId);
            logger.info("getProductList=={}", JsonUtil.toJson(result));
            if (result != null && result.getCode() == 200) {
                List<ProductVO> productVOList = (List<ProductVO>)result.getData();
                DataService.productIdMap = productVOList.stream().collect(Collectors.toMap(ProductVO::getId, p->p));
                logger.info("DataService.productIdMap=={}", JsonUtil.toJson(DataService.productIdMap));

                return productVOList;
            }
        }

        return null;
    }

    public void getIpList(){
        if (DataService.deviceId == null) {
            DataService.deviceId = getMacAddress();
        }
        if (DataService.localIp == null) {
            DataService.localIp = getIP();
        }
        DeviceForm deviceForm = new DeviceForm();
        deviceForm.setDeviceId(DataService.deviceId);
        deviceForm.setIp(DataService.localIp);
        logger.info("DataService.deviceId=={}", DataService.deviceId);
        logger.info("DataService.localIp=={}", DataService.localIp);
        Result result = localRecApiFeign.getIpList(deviceForm);
        if (result.getData() != null) {
            LinkedHashMap getIPResponseVO = (LinkedHashMap) result.getData();
            if (getIPResponseVO.get("branchId") != null) {
                DataService.branchId = (Integer)getIPResponseVO.get("branchId");
            }else {
                DataService.branchId = 76;
            }
            if (getIPResponseVO.get("shopId") != null) {
                DataService.shopId = (Integer) getIPResponseVO.get("shopId");
            }else {
                DataService.shopId = 128;
            }
            if (getIPResponseVO.get("ipList") != null) {
                DataService.ipList = (List<String>) getIPResponseVO.get("ipList");
            }
        }

    }

    public static String getLocalHostIp() throws Exception {
        Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        InetAddress ip = null;
        while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
            //System.out.println(netInterface.getName());
            Enumeration addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                ip = (InetAddress) addresses.nextElement();
                if (ip != null && ip instanceof Inet4Address) {
                    System.out.println("本机的ip=" + ip.getHostAddress());
                    if (ip.getHostAddress().startsWith("192")
                            || ip.getHostAddress().startsWith("10")
//                            || ip.getHostAddress().startsWith("172")
                            ) {
                        return ip.getHostAddress();
                    }
                    break;
                }
            }
        }
        return ip.getHostAddress();
    }


    private String getIP() {
        String ip = null;
        try {
            ip = getLocalHostIp();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ip;
    }

    public static String getMacAddress()
    {
        String mac = "";
        String line = "";

        String os = System.getProperty("os.name");

        logger.info("os.name===={}", os);
        try
        {
            if (os != null && os.startsWith("Windows"))
            {

                    String command = "cmd.exe /c ipconfig /all";
                    Process p = Runtime.getRuntime().exec(command);

                    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

                    while((line = br.readLine()) != null)
                    {
                        if (line.indexOf("Physical Address") > 0)
                        {
                            int index = line.indexOf(":") + 2;

                            mac = line.substring(index);

                            break;
                        }
                    }

                    br.close();
            }else {
                String command = "ifconfig";
                Process p = Runtime.getRuntime().exec(command);

                BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

                while((line = br.readLine()) != null)
                {
                    if (line.indexOf("Physical Address") > 0)
                    {
                        int index = line.indexOf(":") + 2;

                        mac = line.substring(index);

                        break;
                    }
                }

                br.close();
            }
        } catch (IOException e) {}

        return mac;
    }

    public String getMacAddress(String host)
    {
        String mac = "";
        StringBuffer sb = new StringBuffer();

        try
        {
            NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getByName(host));

            byte[] macs = ni.getHardwareAddress();

            for(int i=0; i<macs.length; i++)
            {
                mac = Integer.toHexString(macs[i] & 0xFF);

                if (mac.length() == 1)
                {
                    mac = '0' + mac;
                }

                sb.append(mac + "-");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        mac = sb.toString();
        mac = mac.substring(0, mac.length()-1);

        return mac;
    }

    private List<ProductYpRef> getYpProductList() throws Exception{
        if (DataService.branchId != null) {
            Result result = localRecApiFeign.getYpProductList(DataService.branchId);
            logger.info("getYpProductList=={}", JsonUtil.toJson(result));
            if (result.getCode() == 200) {
                if (result.getData() != null) {
                    List<ProductYpRef> productYpRefList = (List<ProductYpRef>)result.getData();
                    DataService.productYpRefMap
                            = productYpRefList.stream().collect(Collectors.toMap(ProductYpRef::getSearchCode, p->p));
                    return productYpRefList;
                }
            }
        }

        return null;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        getIpList();

        File branchIdFile = new File(DataService.imgPath + File.separator + "branchId.txt");

        if (branchIdFile.exists()) {
            BufferedReader fileReader = new BufferedReader(new FileReader(branchIdFile));
            String branchId = fileReader.readLine();
            if (branchId != null) {
                DataService.branchId = Integer.valueOf(branchId);
            }
        }



        File shopIdFile = new File(DataService.imgPath + File.separator + "shopId.txt");

        if (shopIdFile.exists()) {
            BufferedReader fileReader = new BufferedReader(new FileReader(shopIdFile));
            String shopId = fileReader.readLine();
            if (shopId != null) {
                DataService.shopId = Integer.valueOf(shopId);
            }
        }

        updateProductData();
    }

    private void updateProductData()throws Exception{
        getProductList();
        getYpProductList();
    }
}
